package cn.edu.njust.alg.leetcode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import cn.edu.njust.utils.ListUtils;

/**
 * 创建时间：2015年6月15日 上午11:47:37 项目名称：AlgorithmExercise
 * 
 * @author Zhou Xiumin
 * @version 1.0
 * @since JDK 1.7.0_21 文件名称：Leetcode_0_t.java 类说明：
 */
public class Leetcode_22_Generate_Parentheses {

	public static void build(Stack<Character> st1, Stack<Character> st2,
			StringBuffer sb, List<String> list) {
		if (st1.isEmpty() && st2.isEmpty()) {
			list.add(sb.toString());
		}
		if (!st1.isEmpty()) {
			Character character = st1.pop();
			sb.append(character);
			build(st1, st2, sb, list);
			st1.push(character);
			sb.deleteCharAt(sb.length() - 1);

		}
		if (!st2.isEmpty() && st2.size() > st1.size()) {
			Character character = st2.pop();
			sb.append(character);
			build(st1, st2, sb, list);
			st2.push(character);
			sb.deleteCharAt(sb.length() - 1);
		}

	}

	public static List<String> generateParenthesis(int n) {
		List<String> list = new ArrayList<String>();
		Stack<Character> st1 = new Stack<Character>();
		Stack<Character> st2 = new Stack<Character>();
		for (int i = 0; i < n; i++) {
			st1.push('(');
			st2.push(')');
		}
		build(st1, st2, new StringBuffer(), list);
		return list;
	}

	public static void main(String[] args) {
		for (int i = 1; i < 10; i++) {
			List<String> list = generateParenthesis(i);
			System.out.println("count: " + list.size());
			ListUtils.printList(list);
		}

	}

}
